import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import store from '@/store'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/v1',
  timeout: 20000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 统一错误处理
    if (error.response.status === 401) {
      Message.error('登录信息已过期，请重新登录')
      store.dispatch('user/logout')
      router.push('/login')
      // 返回一个错误Promise对象
      return Promise.reject(error)
    } else {
      Message({ message: error.response.data.msg, type: 'error' })
      return Promise.reject(error)
    }
  }
)

export default service
